// Copyright (c) 2009 Paul Kohler
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
// and associated documentation files (the "Software"), to deal in the Software without restriction, 
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do 
// so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial 
// portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace FileSystemDatabase
{
	/// <summary>
	/// A file system database implementation using XML.
	/// </summary>
	public class XmlDatabase : FileSystemDatabase
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="XmlDatabase"/> class.
		/// </summary>
		/// <param name="basePath">The base path of the file system database.</param>
		public XmlDatabase(string basePath)
			: base(basePath)
		{
			FileExtension = "xml";
		}

		/// <summary>
		/// Serializes the specified object as an XML string for writing to disk.
		/// </summary>
		/// <param name="row">The row.</param>
		/// <returns>
		/// An XML string representation of the object.
		/// </returns>
		protected override string Serialize(object row)
		{
			using (StringWriterWithEncoding sw = new StringWriterWithEncoding(Encoding.UTF8))
			{
				XmlSerializer serializer = new XmlSerializer(row.GetType());
				serializer.Serialize(sw, row);
				return sw.ToString();
			}
		}

		/// <summary>
		/// Deserializes the XML <paramref name="fileData"/> string into an object of type <paramref name="rowType"/>.
		/// </summary>
		/// <param name="rowType">Type of the row.</param>
		/// <param name="fileData">The object as an XML string.</param>
		/// <returns>An instance of the object.</returns>
		protected override object Deserialize(Type rowType, string fileData)
		{
			using (StringReader sr = new StringReader(fileData))
			{
				XmlSerializer serializer = new XmlSerializer(rowType);
				return serializer.Deserialize(sr);
			}
		}
	}
}